package com.gamecat.android_tools.network

import android.util.Log
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

class HttpRequest<ApiService> {
    //请求超时时间5S
    private val connectionTimeoutTime = 60L
    private val httpLoggingInterceptor = HttpLoggingInterceptor().setLevel(

        HttpLoggingInterceptor.Level.BODY
//        else HttpLoggingInterceptor.Level.NONE
    )

    //构造OkhttpBuilder
    private val okhttBuilder: OkHttpClient.Builder =
        OkHttpClient.Builder()
            .addNetworkInterceptor(httpLoggingInterceptor)
            .addInterceptor(LogInterceptor())
            //链接超时设置
            .connectTimeout(connectionTimeoutTime, TimeUnit.SECONDS)
            //读取超时时间设置
            .readTimeout(connectionTimeoutTime, TimeUnit.SECONDS)
            .writeTimeout(connectionTimeoutTime, TimeUnit.SECONDS)
            //默认重试一次，若需要重试N次，则要实现拦截器。
            .retryOnConnectionFailure(true)



    class LogInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            var request = chain.request()
            Log.i(
                "wxf",
                " Requeste " + "\nmethod:" + request.method() + "\nurl:" + request.url() + "\nbody:" + request.body().toString()
            )


            var response = chain.proceed(request)
            Log.i(
                "wxf",
                " Response " + "\nsuccessful:" + response.isSuccessful + "\nbody:" + response.peekBody(
                    1024
                )?.string()
            )

            return response
        }

    }

    /**
     * 发起网络请求
     */
    private fun buildOkHttpClient(): OkHttpClient {
        return this.okhttBuilder.build()
    }

    /**
     * 构建ApiService
     */
    fun buildApiService(apiService: Class<ApiService>, baseurl: String): ApiService {
        return Retrofit
            .Builder()
            .client(buildOkHttpClient())
            .baseUrl(baseurl)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build().create(apiService)
    }

}